//
//  BaseWebViewController.m
//  Builder
//
//  Created by JCK on 2017/12/7.
//  Copyright © 2017年 JCK. All rights reserved.
//

#import "BaseWebViewController.h"
#import <WebKit/WebKit.h>
#import "Tool.h"

#import "JCKSubWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "SVProgressHUD.h"
#import "BaseSocketManager.h"
@interface BaseWebViewController ()<WKUIDelegate,WKNavigationDelegate,UICollectionViewDelegate,UINavigationControllerDelegate,BaseSocketManagerDelegate>
{
    NSString *trckingID;
    WKWebView *weWebView;
    UIProgressView *progress;
}
@property (nonatomic, assign) BOOL isPost; // 定义一个变量

@property (nonatomic, strong) UIButton *rightBtn;

@end

@implementation BaseWebViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (weWebView)
    {
        [weWebView reload];
    }
    
    
//    if ([self.title isEqualToString:@"找工匠"]){
    
//        [self.navigationController setNavigationBarHidden:YES];
    
//    }else{
        [self.navigationController setNavigationBarHidden:NO];
//    }
    
    //    //TODO:加载
    //    [weWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    //
    //    //TODO:kvo监听，获得页面title和加载进度值
    //    [weWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    //    [weWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self showCustomNavigationBackButton];
    // Do any additional setup after loading the view.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloData:) name:Socket1003 object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloData:) name:Socket1006 object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloData:) name:Socket1008 object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloData:) name:Socket1014 object:nil];
    
    
    [SVProgressHUD showWithStatus:@"加载中..."];
    
    weWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    weWebView.navigationDelegate = self;
    weWebView.UIDelegate = self;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_urlStr]];
    [weWebView loadRequest:request];
    [self.view addSubview:weWebView];
    
    
    // socket
    BaseSocketManager *socketManager = [BaseSocketManager shareInstance];
    socketManager.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(vmSiteshow) name:@"vmSiteshow" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(vmSiteshow) name:@"addSuccess" object:nil];
    //    [weWebView evaluateJavaScript:@"iOSCallJsAlert()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
    //
    //        NSLog(@"value: %@ error: %@", response, error);
    //    }];
    //添加收藏的按钮
    [self CollectionOrderInfo];
}

#pragma mark - 订单的收藏
- (void) CollectionOrderInfo {
    
    if ([_isOrder isEqualToString:@"YES"]) {
        
        //是进入订单
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        rightBtn.frame = CGRectMake(0, 0, 30, 30);
        [rightBtn setBackgroundColor:[UIColor clearColor]];
        [rightBtn setImage:[UIImage imageNamed:@"icon-shoucang-nor"] forState:UIControlStateNormal];
        [rightBtn setImage:[UIImage imageNamed:@"icon-shoucang-sel"] forState:UIControlStateSelected];
        [rightBtn addTarget:self action:@selector(submitBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        _rightBtn = rightBtn;
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        self.navigationItem.rightBarButtonItem = rightItem;
        
    } else if ([_isOrder isEqualToString:@"NO"]) {
        
        //收藏的订单列表
        UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        rightBtn.frame = CGRectMake(0, 0, 60, 30);
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [rightBtn setBackgroundColor:[UIColor clearColor]];
        [rightBtn setTitle:@"管理" forState:UIControlStateNormal];
        [rightBtn setTitle:@"完成" forState:UIControlStateSelected];
        [rightBtn addTarget:self action:@selector(submitBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        _rightBtn = rightBtn;
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        self.navigationItem.rightBarButtonItem = rightItem;
        
    }
    
}

#pragma mark - 调用js方法
- (void) submitBtnClicked:(UIButton *)button {
    button.selected = !button.selected;
    //    [weWebView evaluateJavaScript:@"setDelete()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
    //         NSLog(@"value: %@ error: %@", response, error);
    //    }];
    
    if ([_isOrder isEqualToString:@"NO"]) {
        
        [weWebView evaluateJavaScript:@"setDelete()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            NSLog(@"value: %@ error: %@", response, error);
        }];
        
        
    } else if ([_isOrder isEqualToString:@"YES"]) {
        if (button.selected) {
            //收藏
            [weWebView evaluateJavaScript:@"ordercollection()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                NSLog(@"value: %@ error: %@", response, error);
            }];
            
        } else {
            //取消收藏
            [weWebView evaluateJavaScript:@"cancelcollection()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                NSLog(@"value: %@ error: %@", response, error);
            }];
        }
        
    }
    
}




- (void)vmSiteshow
{
    [weWebView reload];
    [weWebView evaluateJavaScript:@"iOSCallJsAlert()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
    }];
}
// 每一个请求开始发送前都会调用这个方法
// 1, 定义一个全局变量currentRequest,用作保存当前的请求
// 2, 将请求转换成data,然后处理data再将data作为请求数据再次请求
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    if (!_isPost) {
        NSHTTPURLResponse *response = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        if (response.statusCode == 404)
        {
            // 这里处理 404 代码
            NSLog(@"这里处理 404 代码");
        } else if (response.statusCode == 403)
        {
            // 这里处理 403 代码
        } else {
            NSLog(@"这里处理 403 代码");
            _isPost = true;
            [webView loadData:data MIMEType:@"text/html" textEncodingName:@"NSUTF8StringEncoding" baseURL:[request URL]];
            
        }
        return NO;
    }
    else
    {
        NSLog(@"\n\n shouldStartLoadWithRequest请求准备 --  %@ \n\n ",request);
        _isPost = NO;
        return YES;
    }
}
#pragma mark - WebKitDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    
    NSString *path = [[navigationAction.request URL] absoluteString];
    
    path = [path stringByRemovingPercentEncoding];
    NSLog(@"urlString=%@",path);
    if ([path rangeOfString:@"protocol://orderstatus"].location != NSNotFound)
    {
        NSString *encodedValue = [[path substringFromIndex:23] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSData *JSONData = [encodedValue dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",responseJSON);
        trckingID = responseJSON[@"id"];
        NSLog(@"%@",trckingID);
        NSString *PNoStr;
        if ([[NSString stringWithFormat:@"%@",responseJSON[@"Status"]] isEqualToString:@"0"]) // 抢单了
        {
            PNoStr = @"1005";
            
        }
        else if ([[NSString stringWithFormat:@"%@",responseJSON[@"Status"]] isEqualToString:@"6"]) // 取消
        {
            PNoStr = @"1008";
            
        }
        else if ([[NSString stringWithFormat:@"%@",responseJSON[@"Status"]] isEqualToString:@"2"]) // 拒绝
        {
            PNoStr = @"1007";
            
        }
        else if ([[NSString stringWithFormat:@"%@",responseJSON[@"Status"]] isEqualToString:@"3"]) // 辞退
        {
            PNoStr = @"1007";
            
        }
        else if ([[NSString stringWithFormat:@"%@",responseJSON[@"Status"]] isEqualToString:@"5"]) // 付款了
        {
            PNoStr = @"1013";
            
        }
        else if ([[NSString stringWithFormat:@"%@",responseJSON[@"Status"]] isEqualToString:@"4"]) // 发起付款了
        {
            PNoStr = @"1009";
            // 回去订单详情页，并刷新
            
        }
        else
        {
            PNoStr = @"1007"; // 招用
        }
        [[BaseSocketManager shareInstance] sendDataToSocket:trckingID PNo:PNoStr successBlock:^(id responseBody) {
            NSLog(@"%@",responseBody);
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@",responseBody]];
            if ([PNoStr isEqualToString:@"1009"])
            {
                [weWebView goBack];
                [weWebView reload];
            }
            else
            {
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        }];
    }
    if ([path rangeOfString:@"protocol://open"].location != NSNotFound)
    {
        NSString *encodedValue = [[path substringFromIndex:16] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSData *JSONData = [encodedValue dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",responseJSON);
        JCKSubWebViewController *sub = [[JCKSubWebViewController alloc] init];
        sub.title = responseJSON[@"title"];
        NSLog(@"%@",sub.title);
        sub.url = responseJSON[@"url"];
        if ([self.title isEqualToString:@"找工匠"]){
            
            [self.navigationController pushViewController:sub animated:YES];
            self.navigationController.navigationBar.hidden = YES;
        }else{
            [self.navigationController pushViewController:sub animated:YES];
        }
    }
    if ([path rangeOfString:@"getmobilephone"].location != NSNotFound)
    {
        NSString *encodedValue = [[path substringFromIndex:26] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        if (encodedValue.length != 0)
        {
            NSMutableString * str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@",encodedValue];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }
        
    }
    
    //订单是否收藏 urlString=protocol://sendCollection:0
    if ([path rangeOfString:@"protocol://sendCollection:"].location != NSNotFound)
    {
        
        NSString *b = [path substringFromIndex:path.length-1];
        if ([b integerValue] == 1) {
            _rightBtn.selected = YES;
        } else {
            
            _rightBtn.selected = NO;
        }
    }
    
    //订单收藏列表
    if ([path rangeOfString:@"protocol://sendCollection_Delete"].location != NSNotFound)
    {
        
        
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
    [SVProgressHUD dismiss];
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
    [weWebView evaluateJavaScript:@"iOSCallJsAlert()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
    }];
    
    [weWebView evaluateJavaScript:@"sendCollection()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
    }];
    
    [weWebView evaluateJavaScript:@"sendCollection_Delete()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
    }];
    
    
    
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(vmSiteshow) name:@"vmSiteshow" object:nil];
    [SVProgressHUD dismiss];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    ErrorShow(@"加载失败");
  
}

#pragma mark - socketDelegate
- (void)reloData:(NSNotification *)obj
{
    NSLog(@"%@",obj.object);
    [weWebView reload];
    
}

#pragma mark - 我的 -- 根页面导航栏按钮点击实现
//右侧按钮
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
}

//右侧按钮旁边的按钮点击
- (void)onNavigationRightLeftButtonClicked:(UIButton*)sender
{
}
    
//- (void)passValue:(NSString *)value
//{
//    //初始化提示框；
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您有新的订单消息" preferredStyle: UIAlertControllerStyleAlert];
//
//    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        //点击按钮的响应事件；
//        [weWebView reload];
//    }]];
//
//    //弹出提示框；
//    [self presentViewController:alert animated:true completion:nil];
//    [weWebView reload];
//
//}
//#pragma mark KVO的监听代理
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//    NSLog(@"keyPath--%@change--%@context---%@",keyPath,change,context);
//    NSLog(@"wwwww%@",change[@"new"]);
//    //加载进度值
//    if ([keyPath isEqualToString:@"estimatedProgress"])
//    {
//        if (object == weWebView)
//        {
//            [progress setAlpha:1.0f];
//            [progress setProgress:weWebView.estimatedProgress animated:YES];
//            if(weWebView.estimatedProgress >= 1.0f)
//            {
//                [UIView animateWithDuration:0.5f
//                                      delay:0.3f
//                                    options:UIViewAnimationOptionCurveEaseOut
//                                 animations:^{
//                                     [progress setAlpha:0.0f];
//                                 }
//                                 completion:^(BOOL finished) {
//                                     [progress setProgress:0.0f animated:NO];
//                                 }];
//            }
//        }
//        else
//        {
//            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//        }
//    }
//    //网页title
//    else if ([keyPath isEqualToString:@"title"])
//    {
//        if (object == weWebView)
//        {
//            self.title = weWebView.title;
//            if ([self.title isEqualToString:@"打工匠"]) {
//                [self.navigationController setNavigationBarHidden:YES];
//            }
//        }
//        else
//        {
//            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//            NSLog(@"2222%@,change");
//        }
////        self.navigationController.navigationBarHidden=YES;
////        [self.navigationController setNavigationBarHidden:NO];
//    }
//    else
//    {
//        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
//        NSLog(@"11111%@,change");
//    }
//}

//#pragma mark 移除观察者
//- (void)dealloc
//{
//    [weWebView removeObserver:self forKeyPath:@"estimatedProgress"];
//    [weWebView removeObserver:self forKeyPath:@"title"];
//}
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
//
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

